#!/bin/sh

if [ `/sbin/mtx status | grep "Data Transfer Element .:Empty" | wc -l` != 2 ]
then
  echo "There appear to be tapes in the drives.  Please fix before starting backup."
  exit
fi

if [ `/sbin/mtx status | grep "Storage Element .:Full" | wc -l` != 9 ]
then
  echo "The first ten slots have to be full of tapes before this script will run.  Please fix before starting backup."
  exit
fi

if [ `ps ax | grep tar | grep -v grep | wc -l` != 0 ]
then
  echo 'There appears to be a tar already running.  Please kill it before starting backup.'
  exit
fi

trap '{ echo "Killing jobs"; for j in `jobs -p`; do kill $j; done; sleep 3; echo "Unloading tapes"; for t in `ls /logs/current/creating`; do echo $t; /sbin/mtx unload $t 0; done; for t in `ls /logs/current/comparing`; do echo $t; /sbin/mtx unload $t 1; done; sleep 3; mv /logs/current /logs/unknown/`date +%s`; echo "Done"; exit; }' SIGINT

mount | grep /big || mount /big
cd /big

LOGS=/logs/current
DATE=`date +%Y_%m_%d`

mkdir -p /logs/unknown

if [ -e $LOGS ]
then
  mv $LOGS /logs/unknown/`date +%s`
fi

mkdir -p $LOGS/creating
mkdir -p $LOGS/done_create
mkdir -p $LOGS/comparing
mkdir -p $LOGS/done_compare

/usr/local/bin/yz_backup_create.sh $1 > $LOGS/create.log 2>&1 &
/usr/local/bin/yz_backup_compare.sh $1 > $LOGS/compare.log 2>&1 &

wait

/usr/bin/diff $LOGS/create.log $LOGS/compare.log > $LOGS/diff.log

SUMMARY=$LOGS/summary.log

echo 'Used tapes:' > $SUMMARY
cat $LOGS/tapes.log >> $SUMMARY
echo >> $SUMMARY
echo 'Created files:' >> $SUMMARY
wc -l $LOGS/create.log >> $SUMMARY
echo >> $SUMMARY
echo 'Compared files:' >> $SUMMARY
wc -l $LOGS/compare.log >> $SUMMARY
echo >> $SUMMARY
echo 'Differences:' >> $SUMMARY
cat $LOGS/diff.log >> $SUMMARY

cat $SUMMARY | /bin/mail andrewk@yowzaanimation.com -s "Backup summary for $DATE"

mv $LOGS /logs/$DATE

